<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="警告:只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          <span>请选择商品分类：</span>
          <el-cascader
            v-model="paramsValue"
            :options="paramsList"
            :props="paramsProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isDisabled"
            size="mini"
            @click="addParamsVisible = true"
          >添加参数</el-button>
          <el-table :data="manyTableData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(iteam,i) in scope.row.attr_vals"
                  closable
                  @close="tagClose(i,scope.row)"
                  :key="i"
                >{{iteam}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isDisabled"
            size="mini"
            @click="addParamsVisible = true"
          >添加属性</el-button>
          <el-table :data="onlyTableData" style="width: 100%" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(iteam,i) in scope.row.attr_vals"
                  closable
                  @close="tagClose(i,scope.row)"
                  :key="i"
                >{{iteam}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        :title="'添加'+isText"
        :visible.sync="addParamsVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          :model="addCateForm"
          :rules="addCateRules"
          ref="addCateFormRef"
          label-width="100px"
        >
          <el-form-item :label="this.isParams+'名称'" prop="attr_name">
            <el-input v-model="addCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAttr">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        :title="'修改'+isText"
        :visible.sync="editParamsVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :model="editCateForm"
          :rules="editCateRules"
          ref="editCateFormRef"
          label-width="100px"
        >
          <el-form-item :label="this.isParams+'名称'" prop="attr_name">
            <el-input v-model="editCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsVisible = false">取 消</el-button>
          <el-button type="primary" @click="editAttr">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      paramsValue: [],
      paramsList: [],
      paramsProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      activeName: "many",
      onlyTableData: [],
      manyTableData: [],
      addParamsVisible: false,
      editParamsVisible: false,
      addCateForm: {
        attr_name: ""
      },
      editCateForm: {},
      addCateRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      },
      editCateRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getParamsList();
  },
  methods: {
    async getParamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("获取失败");
      } else {
        res.data.forEach(element => {
          element.attr_vals = element.attr_vals
            ? element.attr_vals.split(" ")
            : [];

          element.inputVisible = false;
          element.inputValue = "";
        });
        if (this.activeName === "many") {
          this.manyTableData = res.data;
        } else {
          this.onlyTableData = res.data;
        }
      }
    },
    async getParamsList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 }
      });
      if (res.meta.status != 200) {
        return this.$message.error("获取分类列表失败");
      } else {
        this.paramsList = res.data;
      }
    },
    async handleChange() {
      if (this.paramsValue.length === 3) {
        this.getParamsData();
      } else {
        (this.onlyTableData = []), (this.manyTableData = []);
      }
    },
    async handleClick() {
      this.getParamsData();
    },
    addDialogClose() {
      this.$refs.addCateFormRef.resetFields();
    },
    async addAttr() {
      this.$refs.addCateFormRef.validate(async val => {
        if (!val) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addCateForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status != 201) {
          return this.$message.error("添加参数失败");
        } else {
          this.$message.success("添加参数成功");
          this.addParamsVisible = false;
          this.getParamsData();
        }
      });
    },
    editDialogClose() {
      this.$refs.editCateFormRef.resetFields();
    },
    async editAttr() {
      this.$refs.editCateFormRef.validate(async val => {
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editCateForm.attr_id}`,
          {
            attr_name: this.editCateForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("更新失败");
        }
        this.getParamsData();
        this.editParamsVisible = false;
      });
    },
    async showDialog(attrId) {
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status != 200) {
        return this.$message.error("获取属性失败");
      }
      this.editCateForm = res.data;
      console.log(this.editCateForm);

      this.editParamsVisible = true;
    },
    async deleteParams(attr_id) {
      const result = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (result == "confirm") {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${attr_id}`
        );
        if (res.meta.status != 200) {
          return this.$message.error("删除失败");
        } else {
          this.$message.success("成功删除");
          this.getParamsData();
        }
      } else {
        this.$message.warning("取消删除");
      }
    },
    async handleInputConfirm(params) {
      if (params.inputValue.trim().length === 0) {
        params.inputValue = "";
        params.inputVisible = false;
        return;
      }
      params.attr_vals.push(params.inputValue.trim());
      params.inputValue = "";
      params.inputVisible = false;
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${params.attr_id}`,
        {
          attr_name: params.attr_name,
          attr_sel: params.attr_sel,
          attr_vals: params.attr_vals.join(" ")
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("添加失败");
      }
      this.$message.success("添加成功");
    },
    showInput(input) {
      input.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async tagClose(i, params) {
      params.attr_vals.splice(i, 1);
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${params.attr_id}`,
        {
          attr_name: params.attr_name,
          attr_sel: params.attr_sel,
          attr_vals: params.attr_vals.join(" ")
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
    }
  },
  computed: {
    isDisabled() {
      if (this.paramsValue.length !== 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.paramsValue.length === 3) {
        return this.paramsValue[2];
      }
      return null;
    },
    isText() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
    isParams() {
      if (this.activeName == "many") {
        return "参数";
      } else {
        return "属性";
      }
    }
  }
};
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>